from typing import Union
from fastapi import APIRouter, Body, Depends, Header
from sqlalchemy.orm import Session


from database import get_session
from mldong.auth_middleware import SaIgnore
from mldong.base import R, CommonResult
from modules.sys.params.auth_param import LoginParam
from modules.sys.services.auth_service import AuthService
from modules.sys.vos.auth_vo import LoginToken

tags = ["授权管理"]
router = APIRouter(tags=tags)


def get_auth_service(db: Session = Depends(get_session)) -> AuthService:
    """
    获取权限服务实例的依赖函数
    """
    return AuthService(db)


@router.post("/sys/login", summary="登录", response_model=CommonResult[LoginToken], response_model_exclude_none=True)
@SaIgnore()
async def login(data: LoginParam = Body(description="登录参数"), auth_service: AuthService = Depends(get_auth_service)):
    
    loginToken: LoginToken = auth_service.login(data)
    if not loginToken.token: return R.fail("用户名或密码错误")
    return R.data(loginToken)


@router.post("/sys/logout", summary="退出", response_model=CommonResult, response_model_exclude_none=True)
async def logout(authorization:Union[str,None]=Header(None,description="登录凭证") ,auth_service: AuthService = Depends(get_auth_service)):
    if authorization is None:
        return R.success()
    auth_service.logout(authorization)
    return R.success()
